<template>
  <div>
    <el-form :inline="true">
      <el-form-item prop="name">
        <el-input v-model.trim="searchOffice.name" placeholder="办事处名称"></el-input>
      </el-form-item>
      <el-form-item prop="officeType">
        <el-select v-model="searchOffice.officeType" clearable placeholder="请选择办事处种类">
          <el-option :key="0" label="省办事处" :value="0"></el-option>
          <el-option :key="1" label="市办事处" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="province">
        <el-form-item>
          <v-distpicker @selected="onSearchSelected" :provinceOut="searchOffice.provinceCode" only-province>
          </v-distpicker>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/办事处导入模板.xlsx" download="办事处导入模板.xlsx" style="color:#5a5e66;text-decoration: none "><el-dropdown-item command="handleDownload">模板下载</el-dropdown-item></a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 办事处一览 -->
    <custom-table
      :columns="columns"
      :data="officeList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 办事处模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 办事处新增，修改模态框 -->
    <el-dialog :title="dialogType ==='add'? '新增办事处':'修改办事处信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :model="officeDto" :rules="officeRules" label-width="110px" ref="officeForm">
        <el-form-item label="办事处名称" prop="name">
          <el-input v-model="officeDto.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="办事处种类" prop="officeType">
          <el-select v-model="officeDto.officeType" placeholder="请选择办事处种类">
            <el-option :key="0" label="省办事处" :value="0"></el-option>
            <el-option :key="1" label="市办事处" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="officeDto.contact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="officeDto.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在地区">
          <el-row>
            <el-col :span="9" prop="provinceRule">
              <el-select v-model="officeDto.provinceCode" clearable placeholder="请选择省份" @change="getCity()">
                <el-option
                  v-for="item in allProvince"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="9" prop="cityRule">
              <el-select v-model="officeDto.cityCode" clearable placeholder="请选择城市">
                <el-option
                  v-for="item in allCityInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="officeDto.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logisticsContact">
          <el-input v-model="officeDto.logisticsContact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系电话" prop="logisticsTel">
          <el-input v-model="officeDto.logisticsTel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流地址" prop="logisticsAddr">
          <el-input v-model="officeDto.logisticsAddr" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import store from '@/store'
  import {apiOfficeReadExcel} from '@/api/excel/excelRead'
  import Distpicker from '@/components/distpicker/index'
  import {apiGetOfficeList, apiGetOfficeById, apiAddOffice, apiUpdOffice, apiDelOffice, apiExport} from '@/api/basic/info/inside/office'
  import {baseInfo} from '@/utils/fetch'
  import {apiGetCity} from '@/api/dictionary'
  import {downloadExcel} from "../../../../utils";

  export default {
    name: 'office',
    components: {CustomTable, Distpicker},
    created() {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getOfficeList(listQuery)
      this.getAllProvince()
    },
    data() {
      return {
        dialogVisible: false,                     // 模态框相关数据
        dialogType: '',
        uploadVisible: false,
        hideTable: false,
        searchOffice: {
          name: '',
          officeType: '',
          provinceCode: ''
        },
        listQuery: {
          name: undefined,
          officeType: undefined,
          provinceCode: undefined
        },
        // 所有省份
        allProvince: [],
        // 所有城市
        allCityInfo: [],
        officeDto: {
          name: '',
          officeType: '',
          contact: '',
          tel: '',
          provinceCode: '',
          cityCode: '',
          province: '',
          city: '',
          address: '',
          logisticsContact: '',
          logisticsTel: '',
          logisticsAddr: ''
        },
        officeRules: {
          name: [
            {required: true, message: '请输入办事处名称', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          contact: [
            {required: true, message: '请输入联系人', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          logisticsContact: [
            {required: true, message: '请输入物流联系人', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入联系电话', trigger: 'blur'}
          ],
          logisticsTel: [
            {required: true, message: '请输入物流联系电话', trigger: 'blur'}
          ],
          provinceRule: [
            {required: true, message: '请选择省份', trigger: 'change'}
          ],
          cityRule: [
            {required: true, message: '请选择城市', trigger: 'change'}
          ],
          officeType: [{
            validator: (rule, value, callback) => {
              if (this.officeDto.officeType === '') {
                callback(new Error('请选择办事处种类'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }],
          address: [
            {required: true, message: '请输入详细地址', trigger: 'blur'},
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ],
          logisticsAddr: [
            {required: true, message: '请输入物流地址', trigger: 'blur'},
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ]
        },
        tableLoadingFlag: false,             // 办事处一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '办事处名称', name: 'name', width: '150', align: 'center'},
          {label: '办事处种类', name: 'officeType', width: '100', align: 'center'},
          {label: '省份', name: 'province', width: '100', align: 'center'},
          {label: '城市', name: 'city', width: '100', align: 'center'},
          {label: '详细地址', name: 'address', width: '200', align: 'center'},
          {label: '联系人', name: 'contact', width: '100', align: 'center'},
          {label: '联系电话', name: 'tel', width: '120', align: 'center'},
          {label: '物流联系人', name: 'logisticsContact', width: '100', align: 'center'},
          {label: '物流联系电话', name: 'logisticsTel', width: '120', align: 'center'},
          {label: '物流详细地址', name: 'logisticsAddr', width: '200', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '办事处名称', name: 'officeName', width: '80', height: '40', align: 'center'},
          {label: '办事处种类', name: 'officeType', width: '80', height: '40', align: 'center'},
          {label: '联系人', name: 'contact', width: '80', height: '40', align: 'center'},
          {label: '联系电话', name: 'tel', width: '80', height: '40', align: 'center'},
          {label: '省份', name: 'province', width: '80', height: '40', align: 'center'},
          {label: '城市', name: 'city', width: '80', height: '40', align: 'center'},
          {label: '详细地址', name: 'address', width: '80', height: '40', align: 'center'},
          {label: '物流联系人', name: 'logisticsContact', width: '80', height: '40', align: 'center'},
          {label: '物流联系电话', name: 'logisticsTel', width: '80', height: '40', align: 'center'},
          {label: '物流详细地址', name: 'logisticsAddress', width: '80', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        officeList: [],
        wrongDataList: [],
        pagination: this.getData(this.getOfficeList),
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {}
      }
    },
    methods: {
      excelExport() {
        let paramsPost = {
          name: this.searchOffice.name,
          officeType: this.searchOffice.officeType,
          provinceCode: this.searchOffice.provinceCode
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后办事处信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      handleCommand(command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      onSearchSelected(data) {             // 省市区联动回调
        this.searchOffice.provinceCode = data.province.code
      },
      getOfficeList(listQuery) {
        this.tableLoadingFlag = true
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.searchOffice.provinceCode
        }
        if (listQuery.officeType === undefined) {
          listQuery.officeType = this.searchOffice.officeType
        }
        if (listQuery.name === undefined) {
          listQuery.name = this.searchOffice.name
        }
        apiGetOfficeList(listQuery).then(response => {
          this.officeList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      handleAdd() {
        this.dialogType = 'add'
        this.dialogVisible = true
        this.officeDto = {
          name: '',
          officeType: '',
          contact: '',
          tel: '',
          provinceCode: '',
          cityCode: '',
          province: '',
          city: '',
          address: '',
          logisticsContact: '',
          logisticsTel: '',
          logisticsAddr: ''
        }
        if (this.$refs['officeForm']) {
          this.$refs['officeForm'].resetFields()
        }
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      getCity() {
        this.officeDto.cityCode = ''
        if (this.officeDto.provinceCode === '') {
          this.allCityInfo = []
        }
        let listQuery = {
          province: this.officeDto.provinceCode
        }
        apiGetCity(listQuery).then(response => {
          this.allCityInfo = response.data
        })
      },
      handleEdit(row) {
        apiGetOfficeById(row.id).then(response => {
          this.officeDto.provinceCode = response.data.provinceCode
          this.getCity()
          this.officeDto = response.data
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      submit() {
        this.$refs.officeForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit() {
        apiAddOffice(this.officeDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.cancel()
          this.getOfficeList(this.listQuery)
        })
      },
      updSubmit() {
        apiUpdOffice(this.officeDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.cancel()
          this.getOfficeList(this.listQuery)
        })
      },
      cancel() {
        this.dialogVisible = false
        this.$refs['officeForm'].resetFields()
      },
      searchData() {
        this.listQuery.provinceCode = this.searchOffice.provinceCode
        this.listQuery.officeType = this.searchOffice.officeType
        this.listQuery.name = this.searchOffice.name
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getOfficeList(this.listQuery)
      },
      excelRead(filePath) {
        apiOfficeReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getOfficeList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      // 上传成功后的回调
      uploadSuccess(response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功！'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError(err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload(file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }
        return extension && isLt2M
      },
      handleDel(row) {
        this.$confirm('确定删除该办事处?', '删除办事处', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelOffice(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getOfficeList(this.listQuery)
          })
        }).catch(() => {
        })
      }
    }
  }
</script>
